package com.le.edu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.le.edu.domain.entity.Subject;
import com.le.edu.resp.Result;
import com.le.edu.service.SubjectService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;

/**
 * @author Le
 * @create 2024-04-07 17:26
 */
@RestController
@RequiredArgsConstructor
@Tag(name = "课程分类接口")
@RequestMapping("/subject")
public class SubjectController extends BaseController {
    private final SubjectService subjectService;

    @Operation(summary = "excel导入")
    @PostMapping("/importData")
    public Result<String> importData(@RequestBody MultipartFile file) {
        return Result.ok(subjectService.importData(file));
    }

    @Operation(summary = "课程分类列表")
    @GetMapping("/tree")
    public Result<List<Subject>> listWithTree() {
        return Result.ok(subjectService.listWithTree());
    }

    @Operation(summary = "批量删除")
    @PostMapping("/batchDel")
    public Result<Void> batchDel(@RequestBody Long[] subjectIds) {
        return toAjax(subjectService.removeBatchByIds(Arrays.asList(subjectIds)));
    }

    @Operation(summary = "拖拽更新")
    @PostMapping("/updateDrop")
    public Result<Void> updateDrop(@RequestBody List<Subject> subjects) {
        return toAjax(subjectService.updateBatchById(subjects));
    }

    @CacheEvict(value = "subject", key = "'listWithTree'")
    @Operation(summary = "id删除")
    @DeleteMapping("/{subjectId}")
    public Result<Void> del(@PathVariable("subjectId") Long subjectId) {
        long count = subjectService.count(new LambdaQueryWrapper<Subject>().eq(Subject::getSubjectId, subjectId));
        if (count > 0) {
            subjectService.removeById(subjectId);
            return Result.ok();
        } else {
            return Result.fail("该分类下有子分类，无法删除");
        }
    }

    @CacheEvict(value = "subject", key = "'listWithTree'")
    @Operation(summary = "添加分类")
    @PostMapping
    public Result<Void> add(@RequestBody Subject subject) {
        return toAjax(subjectService.save(subject));
    }

    @CacheEvict(value = "subject", key = "'listWithTree'")
    @Operation(summary = "修改分类")
    @PutMapping
    public Result<Void> update(@RequestBody Subject subject) {
        return toAjax(subjectService.updateById(subject));
    }
}


